/**
 * 入参
    instructType：1-存入   2-支取    3-结息
    详情（存入指令详情、支取指令详情、或结息指令详情）
 * 出参
    点击“保存”成功后，抛出onOK事件；
    点击“取消”按钮，抛出onCancle事件。
*/
import React, { PropTypes, PureComponent, Fragment } from 'react';
import { PrimaryC, DATA_ENTRY, AdvancedSearch, FirstHeaderC, SecondHeaderC, PrimaryGhostC } from '../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Card, Tabs, Spin, Input, Button, message, Table, Divider, DatePicker, Select, Modal } from 'antd';
import style from './index.less';
import SaveOrder from './SaveOrder';
import WithdrawnOrder from './WithdrawnOrder';
import CalcInterestOrder from './CalcInterestOrder';
import CurrentAsset from './CurrentAsset';
import config from './config';
const confirm = Modal.confirm;
import { connect } from 'dva';
import 'moment/locale/zh-cn';
import moment from 'moment';

const { TabPane } = Tabs;
@Form.create()
@connect(({ depositOrderM, globalM, userM: user, loading }) => ({
  depositOrderM,
  globalM,
  user,
  loading,
}))
export default class DepositOrderEdit extends PureComponent {
  static defaultProps = {
    saveClick: () => {},
    cancelClick: () => {},
  };
  state = {
    headBankList: [], //存款总行列表
    //   instructType:'F',//当前tab  //"F" 存入 "i" 支取  "calc" 结息
    typeList: config.typeList, //存款类型
    fundCode: undefined, //组合id
  };

  componentDidMount() {
    const { infoDetail } = this.props;
    // this.getHeadBankList();//查询总行列表
    this.setState({
      fundCode: infoDetail && infoDetail.fundCode ? infoDetail.fundCode : undefined,
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {}

  //保存 获取form表单数据并校验
  saveClick = () => {
    const { instructType } = this.props;
    if (instructType == '1') {
      //存
      const T0 = this.CurrentAsset.state.assetObj.T0 || 0;
      this.SaveOrder.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDepositBalance > T0) {
            message.error('存款金额不能大于T+0资金');
            return;
          }
          this.orderSave(values);
        }
      });
    } else if (instructType == '2') {
      //取
      this.WithdrawnOrder.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('支取本金不能大于存入金额');
            return;
          }
          this.orderSave(values);
        }
      });
    } else {
      //结息
      this.calcInterestOrder.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          if (values.bankDrawDownBalance > values.bankDepositBalance) {
            message.error('结息金额不能大于存入金额');
            return;
          }
          this.orderSave(values);
        }
      });
    }
  };
  //保存请求后台
  orderSave = (params) => {
    const { instructType, infoDetail } = this.props;
    const {
      user: { currentUser = {} },
    } = this.props;
    const {
      globalM: {
        dataDictionary: { C_CUSTODIAN },
      },
    } = this.props;

    let url = 'depositOrderM/tradeBookSave';
    let args = {}; //支取 结息的时候需要存款编号、相关存款的id
    params.tradeInstruction = infoDetail.tradeInstruction;
    params.id = infoDetail.id;
    if (instructType == 2) {
      args.bankDepositNumber = infoDetail.bankDepositNumber;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
    }
    if (instructType == 3) {
      args.bankDepositNumber = infoDetail.bankDepositNumber;
      params.earlyDrawdownDate = moment(params.earlyDrawdownDate).format('YYYYMMDD');
    } else {
      C_CUSTODIAN.map((item) => {
        if (item.value == params.bankTrusteeshipQua) {
          params.bankTrusteeshipQua = item.code;
        }
      });
      params.earlyDrawdown = params.earlyDrawdown !== undefined ? (params.earlyDrawdown == '0' ? 'Y' : 'N') : params.earlyDrawdown;
      params.bankStartDate = moment(params.bankStartDate).format('YYYYMMDD');
      params.bankEndDate = params.bankEndDate ? moment(params.bankEndDate).format('YYYYMMDD') : undefined;
    }
    this.props.dispatch({
      type: url,
      payload: {
        ...params,
        combCode: params.fundCode, //后端只需要一个组合id，不需要产品id，字段与前端的不一致，故修改
        userName: infoDetail.userName || currentUser.name,
        userId: infoDetail.userId || currentUser.userId,
        method: 1, //0是新增 1是修改
        orderSize: instructType == '1' ? 'F' : instructType == '2' ? 'i' : 'calc',
        ...args,
      },
      callback: (type, data) => {
        if (type == 'success') {
          message.success('簿记修改成功!');
          this.props.saveClick('success');
        } else {
          let msg = data.message || '簿记修改失败!';
          message.error(msg);
        }
      },
    });
  };

  //点击取消按钮抛出事件
  cancelClick = () => {
    this.props.cancelClick();
  };
  //获取组合id
  getFundCode = (id, type) => {
    this.setState({
      fundCode: id,
    });
  };
  render() {
    const { headBankList, typeList, fundCode } = this.state;
    const { instructType, infoDetail } = this.props;
    const { loading } = this.props;
    const initComp = (key) => {
      //1-存入   2-支取    3-结息
      if (key === '1')
        return (
          <SaveOrder
            state={3}
            // headBankList={headBankList}
            typeList={typeList}
            onRef={(ref) => (this.SaveOrder = ref)}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeSave')}
            depositInfo={infoDetail}
          />
        );
      if (key === '2')
        return (
          <WithdrawnOrder
            state={3}
            // headBankList={headBankList}
            typeList={typeList}
            onRef={(ref) => (this.WithdrawnOrder = ref)}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeWithdrawn')}
            depositInfo={infoDetail}
          />
        );
      if (key === '3')
        return (
          <CalcInterestOrder
            state={3}
            // headBankList={headBankList}
            typeList={typeList}
            onRef={(ref) => (this.calcInterestOrder = ref)}
            getFundCode={(e) => this.getFundCode(e, 'fundCodeCalc')}
            depositInfo={infoDetail}
          />
        );
    };
    return (
      <div>
        <Spin spinning={loading.effects[`depositOrderM/tradeBookSave`] == true}>
          <div>
            <FirstHeaderC title='当前资金' />
          </div>
          <CurrentAsset onRef={(ref) => (this.CurrentAsset = ref)} fundCode={fundCode} />
          <div style={{ marginTop: '10px' }}>
            <FirstHeaderC title='指令操作' />
          </div>
          {initComp(instructType)}
          <div className={'btnOperate'}>
            <PrimaryC title={'保存'} onClick={this.saveClick} />
            <PrimaryGhostC title={'取消'} onClick={this.cancelClick} />
          </div>
        </Spin>
      </div>
    );
  }
}
